﻿using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class ConvertSpritesToTextures : MonoBehaviour {
	// === Unity ======================================================================================================
	public Sprite Sprite;

	private void Awake() {
		if (Sprite == null) {
			throw new ArgumentException("Sprite is null");
		}
	}

	private void Start() {
		var spriteSheet = AssetDatabase.GetAssetPath(Sprite);
		var sprites = AssetDatabase.LoadAllAssetsAtPath(spriteSheet).OfType<Sprite>().ToArray();
		var number = 1;
		foreach (var sprite in sprites) {
			print(number++ + " ... " + sprites.Length);
			SavePNG(sprite);
		}
		print("Finished");
	}

	// === Private ====================================================================================================
	private string _path = "";

	private void SavePNG(Sprite sprite) {
		var width = (int)sprite.rect.width;
		var height = (int)sprite.rect.height;
		var texture = new Texture2D(width, height, TextureFormat.RGB24, false);
		var pixels = sprite.texture.GetPixels((int)sprite.textureRect.x, (int)sprite.textureRect.y,
											  (int)sprite.textureRect.width, (int)sprite.textureRect.height);
		texture.SetPixels(pixels);
		texture.Apply();
		// Encode texture into PNG
		var bytes = texture.EncodeToPNG();
		Destroy(texture);
		if (!HasPath()) {
			UpdatePath();
		}
		var texturePath = _path + "/" + sprite.name + ".png";
		File.WriteAllBytes(texturePath, bytes);
		AssetDatabase.ImportAsset(texturePath);
	}

	private bool HasPath() {
		return _path != "";
	}

	private void UpdatePath() {
		_path = Application.dataPath + "/Converted Sprites to Textures";
		if (!Directory.Exists(_path)) {
			var guid = AssetDatabase.CreateFolder("Assets", "Converted Sprites to Textures");
			_path = AssetDatabase.GUIDToAssetPath(guid);
		}
	}
}